﻿using Kinlo.Entitys;
using Kinlo.MESDocking;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UIWindows.GlobalStatics;
using UIWindows.Models.Devices;
using UIWindows.Tools.Helper;
using XCode;
using XingLucifer.Devices;
using XingLucifer.IBase.Enums;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace UIWindows.Services.PLC_MESHelper
{
    /// <summary>
    /// 装盘开始扫码 托盘扫码
    /// </summary>
    public class PlateScanBarcodeHandler : HelperBase
    {
        PLCBase InjMachine { get; set; }
        ReserveStatic reserveStatic { get; set; }
        MESWinderOutRecordAddRec _mesWinderOutRecord { get; set; }
        
        public PlateScanBarcodeHandler(
            DeviceInteractiveaddressStatic deviceInteractiveaddressStatic,
            DeviceClientModel deviceModel,
            TemporaryStatic temporaryStatic,
            ParameterStatic parameterStatic,
            DeviceConfigStatic deviceConfigStatic,
            SystemConfigStatic systemConfigStatic,
             HomeStatic homeStatic,
             Action<string, string, string, string, string, long, DateTime, string, string, string, string> log, Action<string, string, string> dialog, ReserveStatic _reserveStatic
            ) : base(deviceInteractiveaddressStatic, deviceModel, temporaryStatic, parameterStatic, deviceConfigStatic, systemConfigStatic, homeStatic, log, dialog)
        {
            InjMachine = deviceModel.PLC;
            _mesWinderOutRecord = new MESWinderOutRecordAddRec(_log, _dialog);
            reserveStatic = _reserveStatic;

            //OCV.Meta.TableName = $"OCV_{DateTime.Now:yyyy}{DateTime.Now.GetQuarterly()}";
            //Precharge.Meta.TableName = $"Precharge_{DateTime.Now:yyyy}{DateTime.Now.GetQuarterly()}";
            //Plate.Meta.TableName = $"Plate_{DateTime.Now:yyyy}{DateTime.Now.GetQuarterly()}";

        }
        public override Task Handle()
        {
            //KL21050011Machine InjMachine = null;
            Int16 testResult = 2;
            //List<KNCScannerMachine> Scanner = null;
            try
            {
                //var dicts = ctx.Container.Get<ConcurrentDictionary<string, object>>();
                //var cfg = ctx.Container.Get<CFG>();
                //InjMachine = (KL21050011Machine)dicts.GetOrAdd("InjMachine", InjMachine);
                //Scanner = (List<KNCScannerMachine>)dicts.GetOrAdd("PlateScaner", Scanner);
                //var Counter = ctx.Container.Get<Counter>();
                //var data = ctx.Container.Get<PlateData>();
                //var DB = ctx.Container.Get<RepoBase>();
                //Scanner?.FirstOrDefault().StartScan();
                //var barcode = Scanner?.FirstOrDefault().Receive().Trim();
                DeviceClientModel? device = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == _deviceModel.ServiceName
            && x.TaskType == TaskTypes.预充装盘开始扫码);

                if (device == null)
                {
                    RunLog($"-预充装盘开始扫码 触发设备位置找不到，请注意!!!", MessageLevelType.错误);
                    return Task.CompletedTask;
                }
                var barcode = ScanCode(_parameterStatic.RunParameter.Retries_Count_ScanCode, device.Communication, 1);

                if (string.IsNullOrWhiteSpace(barcode))
                {
                    testResult = 2;
                    RunLog($"【预充装盘开始扫码】扫码失败");
                }
                else
                {
                    testResult = 1;
                    var dateTimeTicks = DateTime.Now.Ticks;
                    reserveStatic.PlateScanBarcodeStatic.TrayBarcode = barcode;
                    reserveStatic.PlateScanBarcodeStatic.TrayBarcodeID = dateTimeTicks;
                    reserveStatic.PlateScanBarcodeStatic.TrayBarcodeTime = DateTime.Now;

                    _parameter.TrayBarcode = barcode;
                    _parameter.TrayBarcodeID = dateTimeTicks;

                    _temporaryStatic.mesCollectionItemsTemporary[(int)machineInfo_Type].TrayBarcode = barcode;
                    OCV.Meta.TableName = $"OCV_{startTime:yyyy}{startTime.GetQuarterly()}";
                    Precharge.Meta.TableName = $"Precharge_{startTime:yyyy}{startTime.GetQuarterly()}";
                    Plate.Meta.TableName = $"Plate_{startTime:yyyy}{startTime.GetQuarterly()}";


                    var plateData=Plate.FindAll(Plate._.TrayBarcode == barcode);
                    if(plateData!= null&& plateData.Count>0)
                    {
                        plateData.ToList().ForEach(x =>
                        {
                            x.Status = 1;
                        });
                        plateData.Update();
                    }
                    RunLog($"【装盘扫码】扫码成功 {barcode}");
                }

            }
            catch (Exception ex)
            {
                RunLog($"【装盘扫码】发生异常:{ex}");
            }
            finally
            {
                var r1 = InjMachine.Write<short>("DM1207", new short[] { testResult }); ///成功写1，失败写0
                var r2 = InjMachine.Write<short>("DM1206", new short[] { 1 });       //扫描完成信后写入
                var r3 = InjMachine.Write<short>("DM1006", new short[] { 0 });          //PLC作业握手
                RunLog($"【装盘扫码】写结果信号 {testResult} {r1}.{r2}.{r3} {(r1 && r2 && r3 ? "成功" : "失败")}");
            }
            return base.Handle();
        }
    }
}
